package com.example.common.security;

import com.example.common.security.exception.CaptchaException;
import com.example.common.utils.RequestContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.session.SessionAuthenticationException;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: springsecurity-study
 * @description: 自定义失败处理器
 * @author: ChenZhiXiang
 * @create: 2019-07-28 17:46
 **/
@Component
@Slf4j
public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                                        AuthenticationException authenticationException){
        log.info("登录失败");
        Map<String,Object> map = new HashMap<>();
        map.put("code",500);
        if (authenticationException instanceof UsernameNotFoundException || authenticationException instanceof BadCredentialsException) {
            map.put("msg","用户名或密码错误");
        } else if (authenticationException instanceof DisabledException) {
            map.put("msg","用户已被禁用");
        } else if (authenticationException instanceof LockedException) {
            map.put("msg","账户被锁定");
        } else if (authenticationException instanceof AccountExpiredException) {
            map.put("msg","账户过期");
        } else if (authenticationException instanceof CredentialsExpiredException) {
            map.put("msg","证书过期");
        } else if (authenticationException instanceof CaptchaException) {
            map.put("msg",authenticationException.getMessage());
        } else if (authenticationException instanceof SessionAuthenticationException){
            map.put("msg","用户已在其他地方登录");
        } else {
            map.put("msg","登录发生了未知异常");
        }
        RequestContextUtil.writeToResponse(map);
    }
}
